package business.inhospitalqc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import common.Data;
import common.RunCaseJson;
import io.restassured.response.Response;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.testng.annotations.Test;
import utils.GetFileMess;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import static common.Login.login;

public class LaunchQc {
    Logger log = Logger.getLogger(LaunchQc.class);
    public static final String timestamp = String.valueOf(System.currentTimeMillis());
    public static final String system = "env.properties";
    Data data = login();
    /*单病种质控指标模板新增
     * */
    public String CreateModel(String url) {
        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("groupId", "100");
        json.put("timeScope", "2");    //
        json.put("status", "2");
        json.put("version", "7");    //版本：4数据目录筛选，5天塔筛选，6科研/临床/病例讨论筛选，7质控2.0  10事件筛选  11 队列筛选
        json.put("dataIds", "248,249,258,3502,724,893,2852,2909,2781,4310,1516,1519,1523,511,1560,1548,5771,5772,15140,15141,2884,2887,2898,2908,1555,3294,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648,5649,5650,5292,4161,4316,5774,14968,1513,909,3445,1171,3163,15070,15071,15072,15073,3530,3531,3532,3533,3534,3535,3536,15937");
        json.put("whereResult", "{\"logicSymbol\":\"and\",\"whereList\":[{\"logicSymbol\":\"or\",\"whereType\":1,\"whereList\":[{\"logicSymbol\":\"or\",\"whereList\":[{\"symbol\":\"=\",\"dataValueType\":\"1\",\"dataId\":\"463\",\"dataRId\":\"415\",\"columnValue\":\"2018-04-01,2018-12-31\",\"columnName\":\"INDEX_TIME\",\"columnTitle\":\"住院\",\"columnType\":\"date\",\"dataName\":\"出院时间\"}],\"nextLogicSymbol\":\"and\"},{\"logicSymbol\":\"or\",\"whereList\":[{\"symbol\":\"=\",\"dataValueType\":\"2\",\"dataId\":\"1519\",\"dataRId\":\"1433\",\"columnValue\":\"是\",\"columnName\":\"AECOPD\",\"columnTitle\":\"慢性阻塞性肺疾病急性加重期\",\"columnType\":\"string\",\"dataName\":\"是否AECOPD患者\"}]}]}]}");
        json.put("dataScope", "1");      //	 类型：0全部，1住院，2门诊
        json.put("type", "20");     //类型：0初始模板，1队列模板，10数据目录模板，20数据集
        json.put("templateName", "初始版本" + timestamp);
        json.put("indexRule", "1");     //类型： 0全部，1第一次，2最后一次
        json.put("randomNum", "10");
        json.put("businessVariables", "{\"dataType\":\"5\",\"dataId\":\"5\",\"OPTION\":true}");
        log.info(json.toString());
        Response response = RunCaseJson.runCase(json, "post", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String templateId = jsonObject.getJSONObject("data").getString("id");
        return templateId;   //返回templateid
    }

    /*数据集 - 新增
     * */
    public void CreateModelResult(String templateId, String url) {
        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("templateId", templateId);
        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "post", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
    }

    /*数据集 - 列表
     * */
    public String GetPatientList(String templateId, String url) {
        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("page", "1");
        json.put("size", "10");
        json.put("templateId", templateId);
        json.put("authName",data.getUserName());

        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "get", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        JSONObject pageObject = dataObject.getJSONObject("dataPage");
        JSONArray contenArray = pageObject.getJSONArray("content");
        JSONObject obj = contenArray.getJSONObject(0);
        String inpatientNo = obj.getString("inpatientNo");
        return inpatientNo;
    }

    /*批量创建
     * */

    public String BatchCreate(String templateId, String inpatientNo, String url) {
        JSONObject dataQueryWhereIn = new JSONObject();
        dataQueryWhereIn.put("inpatientNo", inpatientNo);

        JSONObject obj = new JSONObject();
        obj.put("qcCheckOption", "6");
        obj.put("inpatientNo", inpatientNo);
        ArrayList arrayList = new ArrayList();
        arrayList.add(obj);

        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("type", "1");   //1=copd，2=aecopd，3=指标检测图
        json.put("templateId", templateId);    ///api-sourcedata/dmp/template/create获取id
        json.put("resultType", "0");
        json.put("qcCheckOption", "6");    //质量管理措施项目（1-6级）
        json.put("diseaseCode", "COPD-001");
        json.put("dataQueryWhereIn", dataQueryWhereIn.toJSONString());
        json.put("ids", arrayList.toString());

        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "post", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject obj1 = jsonObject.getJSONObject("responseData");
        String batchId = obj1.getString("id");     //返回batchId
        return batchId;
    }

    /*批次获取患者列表*/
    public String BatchGetPatientList(String batchId, String url) {
        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
//        json.put("types", "1");    //图表类型：1=copd，2=aecopd，3=指标检测图
        json.put("taskFlag", "0");  //指派标志：0=未指派，1=已指派
        json.put("makeFlag", "0");   //填写标志：0=未填写，1=已填
        json.put("checkFlag", "0");   //审核标志：0=未审核，1=已审核
        json.put("batchId", batchId);     //批次ID
        json.put("page", "1");
        json.put("size", "10");
        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "get", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject obj=jsonObject.getJSONObject("responseData");
        JSONArray jsonArray = obj.getJSONArray("content");
        JSONObject content = jsonArray.getJSONObject(0);
        String ids = content.getString("ID");   //返回ids
        return ids;
    }

    /*获取医生列表
     * */
    public String GetUserList(String url) {
        JSONObject json = new JSONObject();
        try {
            String keyword = new GetFileMess().getValue("userName", system);
            String orgId = new GetFileMess().getValue("orgId", system);
            json.put("access_token", data.getAccessToken());
            json.put("authToken", data.getAccessToken());
            json.put("uniqu_no", data.getUniquNo());
            json.put("operatorId", data.getUserId());
            json.put("authUserId", data.getUserId());
            json.put("keyword", data.getUserName());
            json.put("page", "1");
            json.put("size", "10");
            json.put("path", "400," + orgId + ",");    //机构path
            json.put("nroleId", "4222");
        } catch ( ConfigurationException e) {
            e.printStackTrace();
        }
        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "get", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject obj = jsonObject.getJSONObject("data");
        JSONArray jsonArray = obj.getJSONArray("content");
        JSONObject contentojb = jsonArray.getJSONObject(0);
        String practitionerId = contentojb.getString("id");  //返回医生id
        return practitionerId;

    }

    /*创建任务
     *
     * */
    public void CreateTask(String practitionerId, String batchId, String ids, String diseaseCode, String url) {
        JSONObject json = new JSONObject();
        json.put("access_token", data.getAccessToken());
        json.put("authToken", data.getAccessToken());
        json.put("uniqu_no", data.getUniquNo());
        json.put("operatorId", data.getUserId());
        json.put("authUserId", data.getUserId());
        json.put("type", "1");   //1=copd，2=aecopd，3=指标检测图
        json.put("practitionerId", practitionerId);   //从api-users/user/list获取userId
        json.put("batchId", batchId);                  //从/qc/batch/batchCreate.json 获取id
        json.put("ids", ids);    //从/qc/batch/patient/list.json 获取id
        json.put("diseaseCode", diseaseCode);
        log.info("请求参数：" + json.toString());
        Response response = RunCaseJson.runCase(json, "post", url);
        String jsonStr = response.asString();
        log.info("响应报文：" + jsonStr);

    }

    @Test
    public void test() {
Class<LaunchQc> b=LaunchQc.class;
        Method[] methods=b.getMethods();
        for (Method a:methods
             ) {
            System.out.println("gawgwg:"+a);
        }

        String modelurl = "http://192.168.0.161:9000/api-sourcedata/dmp/template/create";
        String ModelResulturl = "http://192.168.0.161:9000/api-sourcedata/dmp/template/result/create";
        String PatientListurl = "http://192.168.0.161:9000/api-sourcedata/dmp/template/result/list";
        String BatchCreateurl = "http://192.168.0.161:9000/api-sourcedata/qc/batch/batchCreate.json";
        String BatchPatientListurl = "http://192.168.0.161:9000/api-sourcedata/qc/batch/patient/list.json";
        String UserListurl = "http://192.168.0.161:9000/api-users/user/list";
        String url = "http://192.168.0.161:9000/api-sourcedata/qc/task/create.json";
        String diseaseCode="COPD-001";
        String templateId = CreateModel(modelurl);
        CreateModelResult(templateId, ModelResulturl);
        String inpatientNo = GetPatientList(templateId, PatientListurl);
        String batchId = BatchCreate(templateId, inpatientNo, BatchCreateurl);
        String ids = BatchGetPatientList(batchId, BatchPatientListurl);
        String practitionerId = GetUserList(UserListurl);
        CreateTask(practitionerId, batchId, ids, diseaseCode, url);

    }

}
